﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TouchControls;
using System.Windows.Threading;

namespace TouchExplorer.Views
{
    /// <summary>
    /// Interaction logic for FileBrowser.xaml
    /// </summary>
    public partial class FileBrowser : UserControl, IDisposable
    {
        public ExplorerViewModel Model
        {
            get
            {
                return DataContext as ExplorerViewModel;
            }
        }

        public FileBrowser()
        {
            InitializeComponent();
            var model = new ExplorerViewModel(Dispatcher);
            DataContext = model;
            Loaded += new RoutedEventHandler(FileBrowser_Loaded);
        }        

        void FileBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    if (Model.NeverLoaded) Model.SelectedDirectory = null;
                }));
        }

        public void Dispose()
        {
            if (Model != null)
            {
                Model.Dispose();
                DataContext = null;
            }
        }

        internal void SelectFolder(string folderPath)
        {
            Model.SelectFolder(folderPath);
        }

        private const double scrollBar = 40;
        private const double tile = 110;
        private const double oneColumn = tile + scrollBar;
        private const double twoColumn = (2 * tile) + scrollBar;
        private const double threeColumn = (3 * tile) + scrollBar;

        protected override Size MeasureOverride(Size constraint)
        {
            var ratio = constraint.Width / constraint.Height;

            if (ratio > 1) //Landscape
            {
                MainGrid.ColumnDefinitions[0].MinWidth = twoColumn;
                if (constraint.Width > 1100)
                {
                    MainGrid.ColumnDefinitions[0].MinWidth = threeColumn;
                }
            }
            else //Portrait
            {
                MainGrid.ColumnDefinitions[0].MinWidth = oneColumn;
                if (constraint.Width > 700)
                {
                    MainGrid.ColumnDefinitions[0].MinWidth = twoColumn;
                }
            }

            return base.MeasureOverride(constraint);
        }
    }
}
